﻿using Castle.DynamicProxy;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;

namespace TViewCore
{
    public  class PropertyInterceptor : IInterceptor
    {
        private object obj;
        public PropertyInterceptor(object obj)
        {
            this.obj = obj;
        }
        public void Intercept(IInvocation invocation)
        {

            var methodName = invocation.Method.Name;
            //判断是否是属性的 get,set 方法
            if (methodName.StartsWith("get_") || methodName.StartsWith("set_"))
            {
                PropertyInfo property = obj.GetType().GetProperty(methodName.Substring(4, methodName.Length - 4));
                //get
                if (methodName.StartsWith("get_"))
                {
                    invocation.ReturnValue = property.GetValue(obj, null);
                    //初始化 watcher
                    if(Dep.Target!=null)
                    {
                        Dep.PushWatcher(obj, property.Name,Dep.Target);
                    }
                }
                //set
                else if (methodName.StartsWith("set_"))
                {
                    //判断新值跟旧值是否一致，不一致则更新并通知更新
                    var newValue = invocation.Arguments[0];
                    var oldValue = property.GetValue(obj, null);
                    
                    if (!newValue.Equals(oldValue))
                    {
                        property.SetValue(obj, newValue, null);
                        invocation.ReturnValue = newValue;
                        //Notify
                        Dep.Notify(obj, property.Name);
                    }
                }
            }
            else invocation.Proceed();
        }
    }
}
